package com.example.algorithm.huawei_rongyao_29;

import java.util.Scanner;

// 一种错误的写法演示，来说明int minLength = Integer.MAX_VALUE;的重要性。
// 就以下两点改动，导致程序算出的结果是错的。
// 所以理解了为什么minLength的初始值要设置成最大的整数Integer.MAX_VALUE，因为后面是Math.min(minLength, length)
public class Q15_ShortestPalindromeSubstring02 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        int result = shortestPalindromeSubstringLength(s);
        System.out.println(result);
    }

    public static int shortestPalindromeSubstringLength(String s) {
        int n = s.length();
        int minLength = -1; // 改动之一

        for (int length = 2; length <= n; length++) {
            for (int start = 0; start <= n - length; start++) {
                String substring = s.substring(start, start + length);
                if (isPalindrome(substring)) {
                    minLength = Math.min(minLength, length);
                }
            }
        }
        return minLength; // 改动之二
    }

    public static boolean isPalindrome(String s) {
        int left = 0;
        int right = s.length() - 1;
        while (left < right) {
            if (s.charAt(left) != s.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}



